package com.lagou.rpc.consumer;

import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

@SpringBootApplication
public class ClientBootStrapApplication implements CommandLineRunner {

    @Autowired
    RpcClientProxy rpcClientProxy;

    public static void main(String[] args) {
        SpringApplication.run(ClientBootStrapApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ZkClient zkClient = new ZkClient("192.168.0.131:2181");
                System.out.println("客户端与zookeeper会话被创建了..");
                //客户端对注册在zookeeper上的服务端节点变化进行监听
                zkClient.subscribeChildChanges("/rpcServer", new IZkChildListener() {
                    public void handleChildChange(String serverPath, List<String> serverS) throws Exception {
                        System.out.println(serverPath + "的子节点列表发生了变化,变化后的子节点列表为"+ serverS);
                        List<String> serverInfo = rpcClientProxy.setRpcClient(zkClient, serverS);
                        for (String s : serverInfo) {
                            System.out.println(s);
                        }
                    }
                });
                System.out.println();
            }
        }).start();
    }
}
